package main

import (
	"fmt"
	"github.com/micro/go-micro/v2"
	wrapperTrace "github.com/micro/go-plugins/wrapper/trace/opentracing/v2"
	"github.com/opentracing/opentracing-go"
	"github.com/sirupsen/logrus"
	"log"
	"micro-grpc-server/common"
	"micro-grpc-server/library/logger"
	"micro-grpc-server/library/logger/hooks"
	"micro-grpc-server/library/logger/reports"
	"micro-grpc-server/library/tracer"
	"micro-grpc-server/services/wechat/internal/conf"
	srv "micro-grpc-server/services/wechat/internal/service"
	pb "micro-grpc-server/services/wechat/proto"
	"os"
)

var Config = &conf.Config{
	ServerName: "go.micro.srv.wechat",
}

func init() {
	var env = os.Getenv("GO_SERVER_ENV")
	if len(env) == 0 {
		env = "dev"
	}
	if err := common.LoadYAML(fmt.Sprintf("config/wechat/service.%s.yaml", env), Config); err != nil {
		panic(err)
	}
	logger.NewLogger(Config.Logger).AddHook(hooks.NewDefaultHook(reports.NewMailReport(Config.ServerName, env), logrus.ErrorLevel))
}

func main() {
	trace, i, err := tracer.NewTracer(Config.ServerName, Config.Tracer)
	if err != nil {
		log.Fatal(err)
	}
	defer i.Close()
	opentracing.SetGlobalTracer(trace)

	server := micro.NewService(
		micro.Name(Config.ServerName),
		micro.Version("latest"),
		micro.WrapHandler(wrapperTrace.NewHandlerWrapper(opentracing.GlobalTracer())),
	)
	server.Init()
	if err := pb.RegisterWechatServiceHandler(server.Server(), srv.NewWechatService(Config)); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
	if err := server.Run(); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
